let router = require('koa-router')();
let Cart = require('../models/cart.js');
let User = require('../models/user.js');
let Film = require('../models/film.js');
router.prefix('/cart');

/**
 * 添加到我的购物车
 */
router.post('/addCart', async (ctx) => {
  try {
    let { id } = ctx.request.body;
    if (!id) {
      throw new Error('缺少参数');
    }
    let cart = await Cart.findOne({doubanId: id, userId: ctx.userId});
    if (!cart) {
      let film = await Film.findOne({doubanId: id});
      let user = await User.findOne({userId: ctx.userId});
      let filmObj = {
        original_title: film.original_title,
        coverurl: film.coverurl,
        collect_count: film.collect_count,
        wish_count: film.wish_count,
        genres: film.genres,
        price: film.price,
        poster: film.poster
      };
      await Cart.create({username: user.name, doubanId: id, userId: user.userId, film: filmObj});
    }

    ctx.success({msg: 'add successful'});
  } catch (err) {
    throw err;
  }
});
/**
 * 获取我的购物车
 */
router.get('/getMyCart', async (ctx, next) => {
  try {
    let carts = await Cart.find({userId: ctx.userId});
    ctx.success(carts);
  } catch (err) {
    throw err;
  }
});
module.exports = router;
